<?php
/**
 * User: onwer
 * Date: 11-12-1
 * Time: 下午11:04
 */
 
class File {
    protected $filetype=array('img'=>array('image/gif','image/jpg','image/png','image/jpeg'),'txt'=>array('text/plain'));
    public $nofiletype=array('.php');
    public $ismulti;
    protected $file;
    public $errorinfo;
    public function __construct($file){
        $this->file=$file;
    }
    /**
     * @param string $type
     * @param int $maxsize kb
     * @param int $minsize kb
     * @return bool
     */
    public function checkfile($type='file',$maxsize=2048,$minsize=0){
        $maxsize=$maxsize*1024;
        $minsize=$minsize*1024;

        $issave=array_walk($this->nofiletype,create_function('$val,$key,$filename','return strpos($val,$filename)===-1;'),
            $this->file['name']);
        if(!$issave){
            $this->errorinfo='文件类型受限！';
        }
        $typeok=$type==='file'?true:in_array($this->file['type'],$this->filetype[$type]);
        if(!$typeok){
            $this->errorinfo='文件类型错误！';
        }

        $sizeok=$this->file['size']>$minsize && $this->file['size']<$maxsize ;
        if(!$sizeok){
            $this->errorinfo='文件大小错误！';
        }

        return  $issave && $sizeok && $typeok;
    }
    /**
     * @param string $src 路径  ''  'aa/'
     * @param string $name 名称，可选。若没有，则是默认文件名
     * @return bool|string 失败返回false，成功文件完整路径
     */
    public function save($src,$name=''){
        $info=array(
            '没有错误',
            '文件大小超过了php.ini定义的upload_max_filesize值',
            '文件大小超过了HTML定义的MAX_FILE_SIZE值',
            '文件上传不完全',
            '无文件上传',
            '缺少临时文件夹',
            '写文件失败',
            '上传被其它扩展中断'
        );
        if(empty($name)){
            $name= basename($this->file['name']);
        }
        $uploadfile = $src .$name;

        if(is_uploaded_file($this->file['tmp_name'])&&  move_uploaded_file($this->file['tmp_name'],$uploadfile)){
            $this->errorinfo='上传文件成功！';
            return  str_replace(DOCROOT,'',$uploadfile);
        }else{
            $this->errorinfo='错误： '.$info[$this->file['error']];
        }
        return false;
    }
}
